package com.hat.easyexcel_export.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.hat.easyexcel_export.entity.Car;
import com.hat.easyexcel_export.entity.MonPoint;
import com.hat.easyexcel_export.excel.CustomRowWriteHandler;
import com.hat.easyexcel_export.excel.IndexRowWriteHandler;
import com.hat.easyexcel_export.service.ExcelService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class ExcelServiceImpl implements ExcelService {
    @Override
    public void exportDoseValue(HttpServletResponse response) {
       try {
           setExcelRespProp(response,"车辆信息" );
           List<Car> carList = getCarList();
           String description = "this is a car";
           EasyExcel.write(response.getOutputStream())
                   .registerWriteHandler(new IndexRowWriteHandler(description))
                   .registerWriteHandler(new CustomRowWriteHandler())
                   .head(Car.class)
                   .excelType(ExcelTypeEnum.XLSX)
                   .sheet()
                   .doWrite(carList);
       }
       catch (Exception e){
           e.printStackTrace();
           log.info("excel导出失败");
       }

    }
    /**
     * @Description: 生产模拟数据
     * @Author Huanganting
     * @Date 2022/4/12 17:29
     * @return java.util.List<com.hat.easyexcel_export.entity.Car>
     */
    public List<Car> getCarList(){
        List<Car> cars = new ArrayList<>(10);

        Double lon = 106.00;
        Double lat = 29.0000;
        for (int i = 0; i < 10; i++) {
            Car car = new Car();
            car.setName("车"+ i );
            MonPoint monPoint = new MonPoint();
            monPoint.setLat(lat + i);
            monPoint.setLon(lon + i);
            car.setMonPoint(monPoint);
            car.setPrice((i + lon + lat ) * (i + 1));
            car.setCreateDate(System.currentTimeMillis());
            cars.add(car);
        }
        return cars;
    }
    /**
     * @Description: 设置excel导出响应头
     * @Author Huanganting
     * @Date 2022/4/8 10:27
     * @param response:
     * @param rawFileName:  文件名
     */
    private void setExcelRespProp(HttpServletResponse response, String rawFileName) throws UnsupportedEncodingException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode(rawFileName, "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
    }
}
